package com.leon.alishop.core.service.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leon.alishop.core.cache.CacheManage;
import com.leon.alishop.core.cache.CacheTypeEnum;
import com.leon.alishop.core.service.CityAreaService;
import com.leon.alishop.core.vo.CityAreaParams;
import com.leon.alishop.dao.CityAreaDao;
import com.leon.alishop.model.CityArea;

@Service("cityAreaService")
public class CityAreaServiceImpl implements CityAreaService {

	@Override
	public Map<Integer, CityArea> findAllCityAreaMap() {
		List<CityArea> list = cityAreaDao.findAllCityArea();
		if (list == null || list.size() == 0)
			return Collections.emptyMap();

		Map<Integer, CityArea> ret = new HashMap<Integer, CityArea>(list.size());
		HashSet<String> idLevelSet = new HashSet<String>(list.size());
		for (CityArea c : list) {
			if(c.getLevel()!=null)
				idLevelSet.add(c.getId() + "_" + c.getLevel());
		}
		for (CityArea c : list) {
			if (isValidCityArea(c)){
				if(c.getLevel().intValue()>1 && !idLevelSet.contains(c.getParentId()+"_"+(c.getLevel()-1)))
					continue;
				ret.put(c.getId(), c);
			}
		}
		return ret;
	}
	
	public int insertOrUpdateCityAreaMap(CityAreaParams params){
		if(params == null)
			return 0;
		CityArea area = ((CityArea)params).clone();
		int ret = 0;
		if(area.getId() != null){
			CityArea tmp = cityAreaDao.selectById(area.getId());
			if(tmp == null){
				params.setErrorMsg("未找到该记录！");
				return 0;
			}
			ret = cityAreaDao.updateByIdSelective(area);
		}else{
			ret = cityAreaDao.insertSelective(area);
		}
		if(ret > 0){
			CacheManage.clear(CacheTypeEnum.CITY_AREA);
		}
		return ret;
	}
	
	private boolean isValidCityArea(CityArea c){
		return c !=null 
				&& c.getId()!=null 
				&& c.getLevel()!=null 
				&& (c.getLevel().intValue()==1 || c.getLevel().intValue()==2 || c.getLevel().intValue()==3)
				&& c.getName()!=null
				&& c.getParentId()!=null;
	}

	@Autowired
	private CityAreaDao cityAreaDao;

}
